# -*- coding:utf-8 -*-

# @Time    : 2023/7/30 21:07
# @Author  : zengwenjia
# @Email   : zengwenjia@lingxi.ai
# @Software: LLM_internal

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #


import asyncio
import copy
import json
import math
from common.log import logger
from db.redis.redis_service import RedisMemory
from urllib.parse import urlparse, parse_qs

import aiohttp


async def fetch(session, url, payload):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
        'Content-Type': 'text/javascript; charset=utf-8',
        'Content-Encoding': 'gzip'
    }
    async with session.get(url, params=payload, headers=headers) as response:
        return await response.text()


insurance_coverage_measure_url_dict = {
    30:
        "https://www.huize.com/apps/cps/product/getTrial?callback=jQuery18208315694759126884_1690849737357&uid=10000000&prodId=102688&planId=106126",
    50:
        "https://www.huize.com/apps/cps/product/getTrial?callback=jQuery18208315694759126884_1690849737357&uid=10000000&prodId=102688&planId=106127",
    100:
        "https://www.huize.com/apps/cps/product/getTrial?callback=jQuery18208315694759126884_1690849737357&uid=10000000&prodId=102688&planId=106128",
    150:
        "https://www.huize.com/apps/cps/product/getTrial?callback=jQuery18208315694759126884_1690849737357&uid=10000000&prodId=102688&planId=106129",
}


def round_up_to_nearest(number):
    try:
        number = float(number)
        if number.is_integer():
            number = int(number)
        num_length = len(str(number))

        if num_length <= 3:
            target_position = 10
        elif num_length == 4:
            target_position = 100
        elif num_length == 5:
            target_position = 1000
        elif num_length == 6:
            target_position = 10000
        else:
            return number  # 超过六位数的情况，直接返回原值

        base = target_position
        remainder = number % base
        if remainder == 0:
            return number
        else:
            return number + base - remainder
    except:
        return number


async def choose_coverage_url_and_coefficient(accident_insurance_coverage):
    accident_insurance_coverage = int(accident_insurance_coverage)
    accident_insurance_coverage_coefficient = 1
    if accident_insurance_coverage > 150:
        # 按系数计算大于150万保额的保费
        accident_insurance_coverage_coefficient = float(accident_insurance_coverage / 150)
        accident_insurance_coverage = 150
    elif 100 < accident_insurance_coverage <= 150:
        accident_insurance_coverage = 150
        # 150万保额这一档
    elif 50 < accident_insurance_coverage <= 100:
        accident_insurance_coverage = 100
        # 100万保额这一档
    elif 30 < accident_insurance_coverage <= 50:
        accident_insurance_coverage = 50
        # 50万保额这一档
    elif accident_insurance_coverage <= 30:
        accident_insurance_coverage = 30
    url = insurance_coverage_measure_url_dict.get(accident_insurance_coverage, "")

    return url, accident_insurance_coverage_coefficient


class PremiumCalculation:

    def __init__(self, user_info):
        self.user_info = copy.deepcopy(user_info)
        if "sex" not in self.user_info:
            self.user_info["sex"] = "男"
        else:
            if self.user_info["sex"] not in ["男", "女"]:
                self.user_info["sex"] = "男"

    def check_life_insurance_condition(self):
        has_children_cost = False
        has_parents_cost = False
        if "children_cost" in self.user_info:
            has_children_cost = True
        if "children_age" in self.user_info:
            has_children_cost = True
        if "parents_cost" in self.user_info:
            has_parents_cost = True
        if "parents_num" in self.user_info:
            has_parents_cost = True
        if has_children_cost and has_parents_cost:
            return True
        return False

    def calculate_life_insurance_coverage(self):
        life_insurance_coverage = None
        life_insurance_coverage_num = None

        if self.check_life_insurance_condition():
            remaining_mortgage_loan_amount = 0
            if ("remaining_mortgage_loan_amount" in self.user_info):
                remaining_mortgage_loan_amount = self.user_info["remaining_mortgage_loan_amount"]

            if "children_cost" in self.user_info:
                children_cost = self.user_info["children_cost"]
            else:
                children_age = self.user_info["children_age"]
                if "children_num" in self.user_info:
                    children_num = self.user_info["children_num"]
                else:
                    children_num = len(children_age)

                children_future_living = 0
                children_future_education = 0
                if children_num > 1:
                    if len(children_age) == 1:
                        children_age = [children_age] * children_num
                    for age in children_age:
                        if age < 22:
                            children_future_living = children_future_living + (22 - age) * 12000
                            children_future_education = children_future_education + (22 - age) * 30000
                elif children_num == 1:
                    if children_age < 22:
                        children_future_living = (22 - children_age) * 12000
                        children_future_education = (22 - children_age) * 30000
                children_cost = children_future_living + children_future_education

            if "parents_cost" in self.user_info:
                parental_support = self.user_info["parents_cost"]
            else:
                # "parents_age": [55,53]

                parents_num = self.user_info["parents_num"]
                if "parents_age" not in self.user_info:
                    parents_age = self.user_info["current_age"] + 30
                    if parents_num > 1:
                        parents_age = [parents_age] * parents_num

                else:
                    parents_age = self.user_info["parents_age"]

                parental_support = 0
                if parents_num > 1:
                    for age in parents_age:
                        if age < 85:
                            parental_support = parental_support + (85 - age) * 12000
                elif parents_num == 1:
                    if parents_age < 85:
                        parental_support = (85 - parents_age) * 12000

            life_insurance_coverage_detail = remaining_mortgage_loan_amount + children_cost + parental_support
            life_insurance_coverage_num = int(life_insurance_coverage_detail / 10000)
            life_insurance_coverage = str(life_insurance_coverage_num) + "万"

        return life_insurance_coverage_num, life_insurance_coverage

    # 计算保额
    async def calculate_insurance_coverage(self):
        logger.info("start calculate_insurance_coverage")
        logger.info("user_info is: " + json.dumps(self.user_info, ensure_ascii=False))
        if ("total_expenditure" not in self.user_info) or (
                not isinstance(self.user_info["total_expenditure"], (int, float))):
            return ""

        accident_insurance_coverage = ""
        if ("life_phases" in self.user_info) and (self.user_info["life_phases"] in ["退休期"]):
            accident_insurance_coverage_num = 12
            accident_insurance_coverage = "医疗保额2万左右，身故保额10-20万"
        elif ("total_expenditure" in self.user_info and isinstance(self.user_info["total_expenditure"],
                                                                   (int, float))) and self.user_info[
            "total_expenditure"] > 0:
            accident_insurance_num_tuple = (
                math.ceil(5 * self.user_info["total_expenditure"] * 12 / 10000),
                math.ceil(10 * self.user_info["total_expenditure"] * 12 / 10000))
            accident_insurance_coverage = str(accident_insurance_num_tuple[0]) + "万-" + str(
                accident_insurance_num_tuple[1]) + "万"
            accident_insurance_coverage_num = accident_insurance_num_tuple[0]

        medical_insurance_coverage_num = 5
        medical_insurance_coverage = "5万-10万"

        critical_illness_insurance_coverage = ""
        if ("life_phases" in self.user_info) and (self.user_info["life_phases"] in ["退休期"]):
            critical_illness_insurance_coverage_num = 30
            critical_illness_insurance_coverage = "30 - 40万（重大疾病的平均治疗费用）"
        elif ("total_expenditure" in self.user_info and isinstance(self.user_info["total_expenditure"], (int, float))):
            critical_illness_insurance_coverage_tuple = (
                math.ceil(3 * self.user_info["total_expenditure"] * 12 / 10000),
                math.ceil(5 * self.user_info["total_expenditure"] * 12 / 10000))
            critical_illness_insurance_coverage = str(critical_illness_insurance_coverage_tuple[0]) + "万-" + str(
                critical_illness_insurance_coverage_tuple[1]) + "万"
            critical_illness_insurance_coverage_num = critical_illness_insurance_coverage_tuple[0]

        life_insurance_coverage_num, life_insurance_coverage = self.calculate_life_insurance_coverage()

        insurance_coverage_dict = {}
        insurance_coverage_num_dict = {}
        key_name_map = {
            "accident_insurance_coverage": "意外险保额",
            "medical_insurance_coverage": "医疗险保额",
            "critical_illness_insurance_coverage": "重疾险保额",
            "life_insurance_coverage": "寿险保额",
            "critical_illness_premium": "重疾险保费",
            "medical_insurance_premium": "医疗险保费",
            "accident_insurance_premium": "意外险保费",
            "life_insurance_premium": "寿险保费"
        }
        if accident_insurance_coverage:
            insurance_coverage_dict["accident_insurance_coverage"] = accident_insurance_coverage
            insurance_coverage_num_dict["accident_insurance_coverage"] = accident_insurance_coverage_num
        if medical_insurance_coverage:
            insurance_coverage_dict["medical_insurance_coverage"] = medical_insurance_coverage
            insurance_coverage_num_dict["medical_insurance_coverage"] = medical_insurance_coverage_num
        if critical_illness_insurance_coverage:
            insurance_coverage_dict["critical_illness_insurance_coverage"] = critical_illness_insurance_coverage
            insurance_coverage_num_dict["critical_illness_insurance_coverage"] = critical_illness_insurance_coverage_num
        if life_insurance_coverage:
            insurance_coverage_dict["life_insurance_coverage"] = life_insurance_coverage
            insurance_coverage_num_dict["life_insurance_coverage"] = life_insurance_coverage_num

        solution_info = ""
        if len(insurance_coverage_num_dict) < 2:
            return solution_info

        insurance_plan_dict = {}
        insurance_plan_dict.update(insurance_coverage_dict)

        user_info = copy.deepcopy(self.user_info)
        user_info.update(insurance_coverage_num_dict)
        try:
            premium_calculation = PremiumCalculation(user_info)
            premium_dict = await premium_calculation.total_premium()
            insurance_plan_dict.update(premium_dict)
        except Exception as ee:
            logger.error("premium_calculation error", ee)

        if insurance_plan_dict:
            solution_info = "计算出来适合用户的保险类型、保额及估算的保费是:"
            for key, value in insurance_plan_dict.items():
                solution_info = solution_info + key_name_map[key] + ":" + str(value) + "，"
            solution_info = solution_info + ",基于以上保额及估算的保费(根据市面上常见的部分产品进行的估算)信息，向用户解释推荐的保险类型、保额及保费的原因"
            logger.info(solution_info)
        return solution_info

    async def critical_illness_premium(self):
        age = self.user_info["current_age"]
        birth_year = 2023 - age
        birth_date = str(birth_year) + "-01-01"
        sex = self.user_info["sex"]
        critical_illness_insurance_coverage = self.user_info["critical_illness_insurance_coverage"]
        critical_illness_insurance_coverage = int(critical_illness_insurance_coverage)
        critical_illness_insurance_coverage_coefficient = 1
        if critical_illness_insurance_coverage > 50:
            critical_illness_insurance_coverage_coefficient = float(critical_illness_insurance_coverage / 50)
            critical_illness_insurance_coverage = 50

        critical_illness_insurance_coverage_query = str(
            (math.ceil((critical_illness_insurance_coverage / 5))) * 5) + "万元"

        cookies = {'acw_tc': '2f6a1fc916907294756776161e6d00ef970338155729a78d1e6fea17ec1456'}  # 设置cookie
        async with aiohttp.ClientSession(cookies=cookies) as session:
            restrictGeneParams_value = '{"productId":"102640","productPlanId":"106032","genes":[{"sort":8,"protectItemId":13879,"key":"","value":"' + critical_illness_insurance_coverage_query + '"},{"sort":1,"protectItemId":"","key":"vesterAge","value":"1989-09-24"},{"sort":2,"protectItemId":"","key":"vesterSex","value":"女"},{"sort":3,"protectItemId":"","key":"insureForSelf","value":"否"},{"sort":4,"protectItemId":"","key":"insurantDate","value":"' + birth_date + '"},{"sort":5,"protectItemId":"","key":"sex","value":"' + sex + '"},{"sort":6,"protectItemId":"","key":"insurantJob","value":"1-4类"},{"sort":7,"protectItemId":"","key":"city","value":"110100"},{"protectItemId":"","key":"province","value":"110000"},{"sort":9,"protectItemId":"","key":"paymentType","value":"年交"},{"sort":10,"protectItemId":"","key":"insureAgeLimit","value":"30年"},{"sort":11,"protectItemId":"","key":"insurantDateLimit","value":"终身"},{"sort":12,"protectItemId":"","key":"DeathInsurance","value":"不含"},{"sort":13,"protectItemId":"","key":"diseaseCareInsurance","value":"不含"},{"sort":14,"protectItemId":"","key":"manyTimesWithSeriousIllness","value":"不含"},{"sort":15,"protectItemId":"","key":"malignantTumorInsurance","value":"不含"},{"sort":16,"protectItemId":"","key":"cardiovascularAndCerebrovascularCompensation","value":"不含"},{"sort":17,"protectItemId":"","key":"generalHospitalizationMedicalInsurance","value":"不含"},{"sort":18,"protectItemId":"","key":"policyholderExemption","value":"不含"},{"sort":19,"protectItemId":"","key":"policyholdeExemptionAdditionalInsureAgeLimit","value":"不投保"}],"optGeneOldValue":{"sort":2,"protectItemId":"","key":"vesterSex","value":"男"}}'
            payload = {'restrictGeneParams': restrictGeneParams_value}

            html = await fetch(session,
                               'https://www.huize.com/apps/cps/product/tryTrial?callback=jQuery18202253893763626349_1690721868716&uid=10000000&prodId=102640&planId=106032',
                               payload)
            start_index = html.index("{")
            json_str = html[start_index:]
            json_str = json_str[:-2]
            result = json.loads(json_str)
            preminum = result['data']["preminum"]
            preminum = int(critical_illness_insurance_coverage_coefficient * float(preminum))
            print(preminum)
            if preminum:
                return round_up_to_nearest(preminum)
            return preminum

    async def medical_insurance_premium(self):
        age = self.user_info["current_age"]
        birth_year = 2023 - age
        birth_date = str(birth_year) + "-01-01"
        sex = self.user_info["sex"]

        cookies = {'acw_tc': '2f6a1fc916907294756776161e6d00ef970338155729a78d1e6fea17ec1456'}  # 设置cookie
        async with aiohttp.ClientSession(cookies=cookies) as session:
            restrictGeneParams_value = '{"productId":"102752","productPlanId":"106280","genes":[{"sort":1,"protectItemId":"","key":"insurantDate","value":"' + birth_date + '"},{"sort":2,"protectItemId":"","key":"sex","value":"' + sex + '"},{"sort":3,"protectItemId":"","key":"haveMedical","value":"有"},{"sort":4,"protectItemId":"","key":"insurantDateLimit","value":"1年"},{"sort":5,"protectItemId":"","key":"paymentType","value":"年交"},{"sort":6,"protectItemId":"","key":"insureAgeLimit","value":"1年"},{"sort":7,"protectItemId":"","key":"buyCount","value":"1份"},{"sort":8,"protectItemId":"","key":"offhospitalSpecificDrugTreatment","value":"不含"},{"sort":9,"protectItemId":"","key":"inpatientAllowanceInIntensiveCareUnit","value":"不含"},{"sort":10,"protectItemId":"","key":"onlineConsulTationDrugFee","value":"不含"}],"optGeneOldValue":{"sort":2,"protectItemId":"","key":"sex","value":"男"}}'
            payload = {'restrictGeneParams': restrictGeneParams_value}

            html = await fetch(session,
                               'https://www.huize.com/apps/cps/product/tryTrial?callback=jQuery18204912818634827787_1690848820289&uid=10000000&prodId=102752&planId=106280',
                               payload)
            start_index = html.index("{")
            json_str = html[start_index:]
            json_str = json_str[:-2]
            result = json.loads(json_str)
            preminum = result['data']["preminum"]
            print(preminum)
            if preminum:
                return round_up_to_nearest(preminum)
            return preminum

    async def accident_insurance_premium(self):
        accident_insurance_coverage = self.user_info["accident_insurance_coverage"]

        url, accident_insurance_coverage_coefficient = await choose_coverage_url_and_coefficient(
            accident_insurance_coverage)
        cookies = {'acw_tc': '2f6a1fc916907294756776161e6d00ef970338155729a78d1e6fea17ec1456'}  # 设置cookie
        async with aiohttp.ClientSession(cookies=cookies) as session:
            html = await fetch(session,
                               url, payload={})
            start_index = html.index("{")
            json_str = html[start_index:]
            json_str = json_str[:-2]
            result = json.loads(json_str)
            preminum = result['data']["preminum"]
            preminum = int(accident_insurance_coverage_coefficient * float(preminum))
            print(preminum)
            if preminum:
                return round_up_to_nearest(preminum)
            return preminum

    async def life_insurance_premium(self):
        age = self.user_info["current_age"]
        birth_year = 2023 - age
        birth_date = str(birth_year) + "-01-01"
        sex = self.user_info["sex"]
        life_insurance_coverage = self.user_info["life_insurance_coverage"]

        life_insurance_coverage = int(life_insurance_coverage)
        life_insurance_coverage_coefficient = 1
        if life_insurance_coverage > 200:
            life_insurance_coverage_coefficient = float(life_insurance_coverage / 200)
            life_insurance_coverage = 200

        life_insurance_coverage_query = str(
            (math.ceil((life_insurance_coverage / 10))) * 10) + "万元"

        url = 'https://www.huize.com/apps/cps/product/tryTrial?callback=jQuery18203794057171455172_1690850346301&uid=10000000&prodId=102659&planId=106073'

        restrictGeneParams_value = '{"productId":"102659","productPlanId":"106073","genes":[{"sort":6,"protectItemId":13997,"key":"","value":"' + life_insurance_coverage_query + '"},{"sort":1,"protectItemId":"","key":"insurantDate","value":"' + birth_date + '"},{"sort":2,"protectItemId":"","key":"sex","value":"' + sex + '"},{"sort":3,"protectItemId":"","key":"city","value":"110100"},{"protectItemId":"","key":"province","value":"110000"},{"sort":4,"protectItemId":"","key":"insurantJobN","value":"其他1-6类职业"},{"sort":5,"protectItemId":"","key":"haveSocialSecurity","value":"否"},{"sort":7,"protectItemId":"","key":"insurantDateLimit","value":"30年"},{"sort":8,"protectItemId":"","key":"paymentType","value":"年交"},{"sort":9,"protectItemId":"","key":"insureAgeLimit","value":"10年"},{"sort":10,"protectItemId":"","key":"isInsure","value":"不含"},{"sort":11,"protectItemId":"","key":"isInsureTwo","value":"不含"},{"sort":12,"protectItemId":"","key":"paymentPeriod","value":"不含"},{"sort":13,"protectItemId":"","key":"isInsureThree","value":"不含"},{"sort":14,"protectItemId":"","key":"healthLevel","value":"1"}],"optGeneOldValue":{"sort":7,"protectItemId":"","key":"insurantDateLimit","value":"10年"}}'
        payload = {'restrictGeneParams': restrictGeneParams_value}

        cookies = {'acw_tc': '2f6a1fc916907294756776161e6d00ef970338155729a78d1e6fea17ec1456'}  # 设置cookie
        async with aiohttp.ClientSession(cookies=cookies) as session:
            html = await fetch(session,
                               url, payload=payload)
            start_index = html.index("{")
            json_str = html[start_index:]
            json_str = json_str[:-2]
            result = json.loads(json_str)
            preminum = result['data']["preminum"]
            preminum = int(life_insurance_coverage_coefficient * float(preminum))
            print(preminum)
            if preminum:
                return round_up_to_nearest(preminum)
            return preminum

    async def total_premium(self):
        premium_dict = {}
        if "current_age" not in self.user_info:
            return premium_dict
        if "critical_illness_insurance_coverage" in self.user_info:
            critical_illness_premium = await self.critical_illness_premium()
            premium_dict["critical_illness_premium"] = critical_illness_premium
        if "medical_insurance_coverage" in self.user_info:
            medical_insurance_premium = await self.medical_insurance_premium()
            premium_dict["medical_insurance_premium"] = medical_insurance_premium
        if "accident_insurance_coverage" in self.user_info:
            accident_insurance_premium = await self.accident_insurance_premium()
            premium_dict["accident_insurance_premium"] = accident_insurance_premium
        if "life_insurance_coverage" in self.user_info:
            life_insurance_premium = await self.life_insurance_premium()
            premium_dict["life_insurance_premium"] = life_insurance_premium

        logger.info(premium_dict)
        return premium_dict


async def est_url(url, payload, cookies):
    try:
        async with aiohttp.ClientSession(cookies=cookies) as session:
            html = await fetch(session,
                               url, payload=payload)
            start_index = html.index("{")
            json_str = html[start_index:]
            json_str = json_str[:-2]
            result = json.loads(json_str)
            preminum = result['data']["preminum"]
            print("保费测算结果===" + preminum)
            print(result)
    except Exception:
        print("错误")


def extract_ids_from_url(url):
    try:
        parsed_url = urlparse(url)

        # 获取查询参数
        query_params = parse_qs(parsed_url.query)

        # 获取prodId和planId参数值
        if 'prodId' in query_params and 'planId' in query_params:
            prodId = query_params.get("prodId", [''])[0]
            planId = query_params.get("planId", [''])[0]
            protectItemId = query_params.get("protectItemId", [''])[0]

            return prodId, planId, protectItemId
        else:
            return None, None, None
    except Exception as e:
        print("提取参数时发生错误:", str(e))
        return None, None


def update_primary_dict_by_other(source, target):
    for key, value in source.items():
        # 检查键是否也在字典B中存在
        if key in target:
            # 如果存在，用字典B中的值替换字典A中的值
            source[key] = target[key]

    return source


def replace_dict_keys_with_redis_values(redis_memory, data_dict):
    updated_dict = {}
    # 循环遍历字典中的每个键
    for chinese_key in data_dict.keys():
        # 构建Redis键，添加前缀
        redis_key = chinese_key

        # 查询Redis中的值
        redis_value = redis_memory.get_memory("dict", redis_key)

        # 如果找到对应的值，替换字典中的键
        if redis_value is not None:
            updated_dict[redis_value] = data_dict[chinese_key]
        else:
            # 如果未找到对应值，则保留原始键
            updated_dict[chinese_key] = data_dict[chinese_key]

    return updated_dict


if __name__ == '__main__':
    memory_cache = RedisMemory()

    insurance_product_code = "hz_MSHjxgrqqylbx"

    user_info = {
        "birth_date": "1990-01-01",
        "sex": "男",
    }
    # 长相思
    # insurance_product_need = {
    #     "sex": "男",
    #     "insurantDate": "2000-03-30",
    #     "haveMedical": "有",
    #     "buyCount": "1份",
    #     "insureAgeLimit": "1年",
    #     "offhospitalSpecificDrugTreatment": "不含",
    #     "onlineConsulTationDrugFee": "不含",
    #     "inpatientAllowanceInIntensiveCareUnit": "不含",
    #     "paymentType": "年交",
    # }
    # 小红花
    # critical_illness_insurance_need = {
    #     "sex": "男",
    #     "city": "110100",
    #     "insurantJob": "1-4类",
    #     "province": "110000",
    #     "insurantDate": "2000-03-30",
    #     "haveMedical": "有",
    #     "buyCount": "1份",
    #     "insureAgeLimit": "30年",
    #     "insurantDateLimit": "终身",
    #     "coverageSecond": "含",
    #     "diseaseCareInsurance": "含",
    #     "additionalInsuranceForMalignantTumors": "含",
    #     "cardiovascularAndCerebrovascularCompensation": "含",
    #     "deathOrTotalDisabilityBenefits": "含",
    #     "offhospitalSpecificDrugTreatment": "不含",
    #     "onlineConsulTationDrugFee": "不含",
    #     "inpatientAllowanceInIntensiveCareUnit": "不含",
    #     "paymentType": "年交",
    #     "保额": "40万元"
    # }

    # i无忧
    # critical_illness_insurance_need = {
    #     "sex": "男",
    #     "city": "110100",
    #     "insurantJob": "1-6类",
    #     "province": "110000",
    #     "insurantDate": "2022-09-01",
    #     "haveMedical": "有",
    #     "buyCount": "1份",
    #     "insureAgeLimit": "10年",
    #     "insurantDateLimit": "至70岁",
    #     "coverageSecond": "含",
    #     "diseaseCareInsurance": "含",
    #     "additionalInsuranceForMalignantTumors": "含",
    #     "additionalCompensationForMalignantTumor": "含",# 重度恶性肿瘤扩展保险金
    #     "cardiovascularAndCerebrovascularCompensation": "含",
    #     "deathOrTotalDisabilityBenefits": "含",
    #     "offhospitalSpecificDrugTreatment": "不含",
    #     "onlineConsulTationDrugFee": "不含",
    #     "inpatientAllowanceInIntensiveCareUnit": "不含",
    #     "manyTimesWithSeriousIllness": "含",
    #     "paymentType": "年交",
    #     "保额": "5万元"
    # }

    # 中端医疗险
    # medical_insurance_need = {
    #     "sex": "男",
    #     "insurantJob": "1-4类",
    #     "city": "110100",
    #     "province": "110000",
    #     "insurantDate": "2000-09-01",
    #     "haveMedical": "有",
    #     "buyCount": "1份",
    #     "insureAgeLimit": "趸交",
    #     "insurantDateLimit": "1年",
    #     "paymentType": "年交",
    #     "DeductibleAmount": "15000元",
    #     "DeductibleAmountTwo": "0元",
    #     "isInsureThree": "10000元",
    #     "isInsureTwo": "10000元",
    #     "isInsure": "含"
    # }
    # 高端医疗险
    high_end_medical_insurance_need = {
        "sex": "男",
        "insurantJob": "1-4类",
        "city": "110100",
        "province": "110000",
        "insurantDate": "2000-09-01",
        "haveMedical": "有",
        "buyCount": "1份",
        "insureAgeLimit": "趸交",
        "insurantDateLimit": "1年",
        "paymentType": "一次性",
        "DeductibleAmount": "30000元",
        "emergencyServices": "不含",
        "dentalResponsibility": "不含",
        "physicalExamination": "不含",
        "DeductibleAmountTwo": "0元",
        "isInsureThree": "10000元",
        "isInsureTwo": "10000元",
        "isInsure": "含",
        "hospitalType": "选项二(公立+私立，含昂贵医院)"
    }

    # redis读取配置文件
    product_info = memory_cache.get_memory("insurance_product", insurance_product_code)

    url = product_info.get("insurance_API")
    insurance_params = product_info.get("insurance_params")

    insurance_params = json.loads(insurance_params)

    insurance_params = update_primary_dict_by_other(insurance_params, high_end_medical_insurance_need)

    product_id, productPlanId, protectItemId = extract_ids_from_url(url)

    # 遍历key拼接请求参数
    genes = []
    for key in insurance_params:
        value = insurance_params.get(key, "")
        if key == '基本保额':
            value = insurance_params.get(key, "")
            genes_item = {
                "sort": 1,
                "protectItemId": int(protectItemId),
                "key": "",
                "value": value
            }
        else:
            genes_item = {
                "sort": 1,
                "protectItemId": "",
                "key": key,
                "value": value
            }
        genes.append(genes_item)

    genes = json.dumps(genes, ensure_ascii=False, indent=4)

    restrictGeneParams_value = '{"productId":"' + product_id + '","productPlanId":"' + productPlanId + '","genes":' + genes + '}'

    payload = {'restrictGeneParams': restrictGeneParams_value.replace("\n", "").replace(" ", "")}

    cookies = {'acw_tc': '2f6a1fc916907294756776161e6d00ef970338155729a78d1e6fea17ec1456'}  # 设置cookie
    print(payload)
    asyncio.run(est_url(url, payload, cookies))
